package com.dissertation.service.impl;

import com.dissertation.model.Assets;
import com.dissertation.model.Collections;
import com.dissertation.model.auth.User;
import com.dissertation.pojo.Favorite;
import com.dissertation.pojo.Message;
import com.dissertation.pojo.UnwindCollections;
import com.dissertation.respository.AssetsRepository;
import com.dissertation.respository.CollectionRepository;
import com.dissertation.service.IAssetsFindByKeyword;
import com.dissertation.service.ICollectionService;
import org.apache.poi.xssf.usermodel.*;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@SuppressWarnings("unchecked")
@Service
public class CollectionImpl implements ICollectionService {
    @Autowired
    CollectionRepository collectionRepository;

    @Autowired
    AssetsRepository assetsRepository;

    @Autowired
    IAssetsFindByKeyword findByKeywordService;


    @Override
    public Message addCollection(Map<String, Object> params) {
        Subject subject = SecurityUtils.getSubject();
        User user =(User) subject.getPrincipal();
        if(user==null){
            return Message.createErr("请先登录");
        }
        if(params.get("column")==null||params.get("id")==null){
            return Message.createErr("请选择收藏夹栏目");
        }
        String column = (String) params.get("column");
        Collections collections = collectionRepository.findByColumnAndAdminID(column,user.getId());
        if(collections==null){
            collections = new Collections();
            collections.setAdminID(user.getId());
            collections.setColumn(column);
        }
        List<String> assetsID = (ArrayList<String>)params.get("id");
        List<Favorite> favoriteList = null;
        if(collections.getFavoriteList()!=null){
            favoriteList = collections.getFavoriteList();
        }else{
            favoriteList = new ArrayList<>();
        }
        for (Favorite e1 : favoriteList) {
            if (assetsID.contains(e1.getAssetsID())) {
                assetsID.remove(e1.getAssetsID());
                return Message.createErr("收藏夹已存在该项目");
            }
        }
        List<Favorite> finalFavoriteList = favoriteList;
        for (String e : assetsID) {
            Assets assets = new Assets();
            Favorite favorite = new Favorite();
            assets = assetsRepository.findOne(e);
            if (assets == null) {
                return Message.createErr("未找到项目,请检查传入的ID");
            }
            favorite = assets2favorites(assets);
            finalFavoriteList.add(favorite);
        }
        collections.setFavoriteList(finalFavoriteList);
        return Message.createSuc(collectionRepository.save(collections));
    }

    @Override
    public Message removeCollection(Map<String, Object> params){
        Subject subject = SecurityUtils.getSubject();
        User user =(User) subject.getPrincipal();
        if(user==null){
            return Message.createErr("请先登录");
        }
        if(params.get("column")==null||params.get("id")==null){
            return Message.createErr("请选择收藏夹栏目");
        }
        String column = (String) params.get("column");
        Collections collections = collectionRepository.findByColumnAndAdminID(column,user.getId());
        List<String> assetsID = (ArrayList<String>)params.get("id");
        List<Favorite> favoriteList = collections.getFavoriteList();
        List<Favorite> newFavorite = new ArrayList<>(favoriteList);
        favoriteList.stream().forEach(e->{
            if(assetsID.contains(e.getAssetsID())){
                newFavorite.remove(e);
            }
        });
        collections.setFavoriteList(newFavorite);
        return Message.createSuc(collectionRepository.save(collections));
    }

    @Override
    public Message addColumn(String column) {
        if("".equals(column)||column==null){
            return Message.createErr("请输入收藏夹的名字");
        }
        List<String> columns = getColumns();
        if(columns.contains(column)){
            return Message.createErr("收藏夹栏目重名,请重新输入");
        }
        Subject subject = SecurityUtils.getSubject();
        User user = (User)subject.getPrincipal();
        Collections collections = new Collections();
        collections.setColumn(column);
        collections.setAdminID(user.getId());
        collections.setFavoriteList(new ArrayList<>());
        collectionRepository.insert(collections);
        return Message.createSuc("创建成功");
    }

    @Override
    public List<String> getColumns() {
        Subject subject = SecurityUtils.getSubject();
        User user =(User) subject.getPrincipal();
        if(user==null){
            return null;
        }
        List<Collections> collectionsList = collectionRepository.findByAdminID(user.getId());
        List<String> columnList = new ArrayList<>();
        collectionsList.stream().forEach(e->columnList.add(e.getColumn()));
        return columnList;
    }

    @Override
    public List<Favorite> getFavorites(String column) {
        if("".equals(column)||column==null){
            return null;
        }
        Subject subject = SecurityUtils.getSubject();
        User user = (User)subject.getPrincipal();
        Collections collections = collectionRepository.findByColumnAndAdminID(column,user.getId());
        return collections.getFavoriteList();
    }

    @Override
    public Message removeColumn(String column) {
        Subject subject = SecurityUtils.getSubject();
        Optional<User> user = Optional.ofNullable((User)subject.getPrincipal());
        collectionRepository.deleteByAdminIDAndColumn(user.orElse(null).getId(),column);
        return Message.createSuc("删除成功");

    }

    @Override
    public List<Favorite> searchBykeyword(String keyword) {
        Subject subject = SecurityUtils.getSubject();
        Optional<User> user = Optional.ofNullable((User)subject.getPrincipal());
        List<UnwindCollections> collections = findByKeywordService.findByKeyword(keyword,user.orElse(null).getId());
        List<Favorite> favoriteList = new ArrayList<>();
        collections.stream().forEach(e-> favoriteList.add(e.getFavoriteList()));
        return favoriteList;
    }

    @Override
    public Integer importFavorites(String[] ids, String fileName, HttpServletResponse response) {
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheet = workbook.createSheet("form 1");
        XSSFCellStyle cellStyle =workbook.createCellStyle();
        int rownumber = 0;
        int colnumber = 0;
        XSSFRow row = sheet.createRow(rownumber);
        String[] headers= new String[]{"科研项目名称","第一责任人","项目类型","时间","语义标签"};
        XSSFCell cell = null;
        for(String header:headers){
            cell = row.createCell(colnumber);
            cell.setCellValue(header);
            colnumber++;
        }
        if(ids==null){
            writeExcel(workbook,fileName,response);
            return 0;
        }
        List<Assets> assetsList = assetsRepository.findByIdIn(ids);
        List<Favorite> favoriteList = new ArrayList<>();
        assetsList.forEach(e->{
            Favorite favorite = null;
            favorite = assets2favorites(e);
            favoriteList.add(favorite);
        });
        for(Favorite favorite:favoriteList){
            rownumber++;
            row = sheet.createRow(rownumber);

            cell  = row.createCell(0);
            cell.setCellValue(favorite.getProjectName());

            cell  = row.createCell(1);
            cell.setCellValue(favorite.getAuthor());

            cell  = row.createCell(2);
            cell.setCellValue(favorite.getProjectType());

            cell  = row.createCell(3);
            cell.setCellValue(favorite.getTime());

            cell  = row.createCell(4);
            cell.setCellValue(favorite.getTags().toString());
        }
        writeExcel(workbook,fileName,response);
        return favoriteList.size();
    }


    public Favorite assets2favorites(Assets assets){
        Optional<Assets> assetsOptional = Optional.of(assets);
        Favorite favorite = new Favorite();
        favorite.setAssetsID(assets.getId());
        favorite.setAuthor(assetsOptional.map(Assets::getAuthor).orElse("无"));
        favorite.setProjectName(assetsOptional.map(Assets::getName).orElse("无"));
        favorite.setTime(assetsOptional.map(Assets::getDate).orElse("无"));
        favorite.setProjectType(assetsOptional.map(Assets::getCategoryLeafName).orElse("无"));
        favorite.setTags(assetsOptional.map(Assets::getTag).orElse(new ArrayList<>()));
        return favorite;
    }

    public void writeExcel(XSSFWorkbook workbook, String fileName , HttpServletResponse response){
        try {
            //定义excel名称 ISO-8859-1 防止名称乱码
            String msg = new String(
                    (fileName).getBytes(),"ISO-8859-1");
            response.setContentType("application/vnd.ms-excel");
            response.addHeader("Content-Disposition", "attachment;filename="
                    + msg);
            workbook.write(response.getOutputStream());

        }catch (IOException e){
            e.printStackTrace();
        }
    }
}


